<template>
  <div class="home-container">
    <h1>社交媒体平台 - 首页</h1>
    <p>欢迎回来，{{ user?.username || '用户' }}！</p>
    
    <!-- 简单的导航 -->
    <div class="nav-buttons">
      <el-button @click="$router.push('/posts')">查看动态</el-button>
      <el-button @click="$router.push('/profile')">个人资料</el-button>
      <el-button @click="$router.push('/private-message')">私信</el-button>
      <el-button @click="$router.push('/notification')">
        <el-icon><BellFilled /></el-icon> 通知
      </el-button>
      <el-button @click="logout">退出登录</el-button>
    </div>

    <!-- 简单的动态列表 -->
    <div class="posts-section" v-if="posts.length > 0">
      <h2>最新动态</h2>
      <div v-for="post in posts" :key="post.id" class="post-item">
        <h3>{{ post.username }}</h3>
        <p>{{ post.description }}</p>
        <small>{{ formatTime(post.createTime) }}</small>
        <div class="post-actions">
          <el-button link v-if="!isLiked(post)" @click="likePost(post.id)">
            <el-icon><Star /></el-icon>
            {{ post.likes !== undefined ? post.likes : (post.likedUsers ? post.likedUsers.length : 0) }} 点赞
          </el-button>
          <el-button link v-else @click="unlikePost(post.id)">
            <el-icon><Star /></el-icon>
            已点赞
          </el-button>
          <el-button link @click="toggleComments(post.id)">
            <el-icon><ChatDotRound /></el-icon>
            {{ post.comments !== undefined ? post.comments : (post.commentCount !== undefined ? post.commentCount : (comments[post.id]?.length || 0)) }} 评论
          </el-button>
        </div>
        <div v-if="showComments[post.id]" class="comments-section">
          <div v-for="comment in comments[post.id] || []" :key="comment.id" class="comment-item">
            <b>
              {{
                comment.username ||
                (comment.user && comment.user.username) ||
                (comment.author && comment.author.username) ||
                comment.user ||
                comment.author ||
                '匿名'
              }}
            </b>:
            {{
              comment.content ||
              comment.text ||
              comment.body ||
              comment.message ||
              comment.comment ||
              comment.description ||
              comment.detail ||
              ''
            }}
            <span class="comment-time">{{ formatTime(comment.createTime || comment.targetDate) }}</span>
          </div>
          <el-input v-model="newComment[post.id]" placeholder="写评论..." @keyup.enter="submitComment(post.id)" />
          <el-button size="small" @click="submitComment(post.id)">评论</el-button>
        </div>
      </div>
    </div>
    <div v-else>
      <p>暂无动态</p>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Star, ChatDotRound, BellFilled } from '@element-plus/icons-vue'
import { postApi, commentApi, notificationApi } from '@/utils/api'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const auth = useAuthStore()
const user = ref(auth.user)
const posts = ref([])
const comments = reactive({})
const showComments = reactive({})
const newComment = reactive({})

const fetchPosts = async () => {
  try {
    const res = await postApi.getAll()
    posts.value = res.data || []
    // 初始化评论区
    posts.value.forEach(post => {
      showComments[post.id] = false
      // 调试：打印评论数据结构
      console.log(`Post ${post.id} comments:`, post.comments)
      console.log(`Post ${post.id} commentList:`, post.commentList)
      
      // 确保评论数据是数组 - 优先使用commentList，兼容comments
      if (post.commentList && Array.isArray(post.commentList)) {
        comments[post.id] = post.commentList
      } else if (post.comments && Array.isArray(post.comments)) {
        comments[post.id] = post.comments
      } else {
        comments[post.id] = []
      }
      
      newComment[post.id] = ''
    })
  } catch (e) {
    console.error('获取动态失败:', e)
    ElMessage.error('获取动态失败')
  }
}

const isLiked = post => {
  if (!user.value) return false
  if (post.likedUsers) {
    return post.likedUsers.includes(user.value.username)
  }
  return false
}

const likePost = async postId => {
  try {
    await postApi.like(postId)
    await fetchPosts()
  } catch (e) {
    ElMessage.error('点赞失败')
  }
}

const unlikePost = async postId => {
  try {
    await postApi.unlike(postId)
    await fetchPosts()
  } catch (e) {
    ElMessage.error('取消点赞失败')
  }
}

const toggleComments = postId => {
  showComments[postId] = !showComments[postId]
}

const submitComment = async postId => {
  if (!newComment[postId]) return
  try {
    await commentApi.add(postId, newComment[postId])
    newComment[postId] = ''
    await fetchPosts()
    showComments[postId] = true
  } catch (e) {
    ElMessage.error('评论失败')
  }
}

const formatTime = t => {
  if (!t) return ''
  const d = new Date(t)
  return d.toLocaleString()
}

const logout = () => {
  auth.logout()
  router.push('/login')
}

onMounted(() => {
  fetchPosts()
})
</script>

<style scoped>
.home-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.nav-buttons {
  margin: 20px 0;
}

.nav-buttons .el-button {
  margin-right: 10px;
}

.posts-section {
  margin-top: 30px;
}

.post-item {
  border: 1px solid #eee;
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 5px;
}

.post-item h3 {
  margin: 0 0 10px 0;
  color: #409EFF;
}

.post-item p {
  margin: 10px 0;
}

.post-item small {
  color: #999;
}

.post-actions {
  margin-top: 10px;
}

.post-actions .el-button {
  margin-right: 8px;
}

.comments-section {
  margin-top: 12px;
  background: #fafbfc;
  border-radius: 6px;
  padding: 10px;
}

.comment-item {
  margin-bottom: 6px;
}

.comment-time {
  color: #aaa;
  font-size: 12px;
  margin-left: 8px;
}
</style> 